// src/browser-manager.ts
import { chromium, Browser, Page, devices } from 'playwright';
import { v4 as uuidv4 } from 'uuid';
import { doInvoice } from './invoice.ts';

interface BrowserSession {
  id: string;
  browser: Browser;
  page: Page;
  url: string;
  isActive: boolean;
}
const iPhone = devices['iPhone 12 Pro'];

export class BrowserManager {
  private sessions = new Map<string, BrowserSession>();

  async createSession(startUrl: string = 'https://www.google.com'): Promise<string> {
    const browser = await chromium.launch({
      headless: false, // 关键：显示浏览器窗口（在服务器上可见）
      args: [
        '--no-sandbox',
        '--disable-setuid-sandbox',
        '--disable-gpu',
        '--window-position=0,0',
        '--window-size=1280,720',
        '--disable-dev-shm-usage',
        '--disable-background-timer-throttling',
        '--disable-renderer-backgrounding',
        '--disable-backgrounding-occluded-windows'
      ]
    });

    const context = await browser.newContext({
      ...iPhone
    });
    const page = await context.newPage();
    await page.goto(startUrl, { waitUntil: 'domcontentloaded' });
    if (startUrl.includes('invoice')) {
      await doInvoice(page, startUrl);
    }
    const sessionId = uuidv4();

    const session: BrowserSession = {
      id: sessionId,
      browser,
      page,
      url: startUrl,
      isActive: true
    };

    this.sessions.set(sessionId, session);
    console.log(`✅ Session created: ${sessionId}`);

    return sessionId;
  }

  getSession(sessionId: string): BrowserSession | undefined {
    return this.sessions.get(sessionId);
  }

  async destroySession(sessionId: string): Promise<boolean> {
    const session = this.sessions.get(sessionId);
    if (!session) return false;

    await session.browser.close();
    this.sessions.delete(sessionId);
    console.log(`🗑️ Session destroyed: ${sessionId}`);
    return true;
  }

  getAllSessions() {
    return Array.from(this.sessions.values()).map(s => ({
      id: s.id,
      url: s.url,
      isActive: s.isActive
    }));
  }
}